package textProcessor;

import java.util.*;

public class AnagramFinder {

    private static Set<String> convertTextToSetOfUniqueWords(String text) {
        String[] words = text.toLowerCase().split(
                "(\\s+|^)\\p{Punct}+|\\p{Punct}+(\\s+|$)(\\p{Punct}+)?|\\s+");
        Set<String> uniqueWords = new HashSet<>();
        for (String word : words) {
            if (word.matches("([a-zа-яё]+[-'])*[a-zа-яё]+'?"))
                uniqueWords.add(word);
        }
        return uniqueWords;
    }

    public static List<List<String>> findAnagrams(String text) {

        if (text == null)
            throw new IllegalArgumentException("Argument value null is not allowed");

        List<List<String>> listOfAllAnagrams = new ArrayList<>();
        Set<String> words = convertTextToSetOfUniqueWords(text);

        if (words.size() <= 1)
            return listOfAllAnagrams;

        Map<String, List<String>> wordStructureMap = new HashMap<>();

        for (String word : words) {

            char[] charSet = word.toCharArray();
            Arrays.sort(charSet);
            String sortedWord = new String(charSet);

            List<String> anagrams = wordStructureMap.get(sortedWord);
            if (anagrams == null) {
                anagrams = new ArrayList<>();
                wordStructureMap.put(sortedWord, anagrams);
            }
            anagrams.add(word);
        }

        for (String key : wordStructureMap.keySet()) {
            List<String> anagrams = wordStructureMap.get(key);
            if (anagrams.size() > 1)
                listOfAllAnagrams.add(anagrams);
        }
        return listOfAllAnagrams;
    }
}
